package cn.com.bod.fas.common.interceptor;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class OpHistoryCacheService {
	
	private static final Logger logger = LoggerFactory.getLogger(OpHistoryCacheService.class);

	public static final ThreadLocal<Connection> connThreadLocal = new ThreadLocal<>();
	
	public List<String> getFields(String table){
		List<String> columnNames = new ArrayList<>();
        //与数据库的连接
        Connection connection = null;
        PreparedStatement statement = null;
        
        String sql = "select * from " + table; 
        
		try {
			if (connThreadLocal.get() == null) {
				return null;
			}
			connection = connThreadLocal.get();
			statement = connection.prepareStatement(sql);
			ResultSetMetaData rsmd = statement.getMetaData();
			//表列数
            int size = rsmd.getColumnCount();
            for (int i = 0; i < size; i++) {
                columnNames.add(rsmd.getColumnName(i + 1));
            }
			return columnNames;
		} catch (SQLException e) {
			logger.error("查询表得全部字段失败！",e.getMessage());
		} finally {
			try {
				if (statement != null) {
					statement.close();
				}
			} catch (SQLException e) {
				logger.error("关闭statement失败！",e.getMessage());
			}
		}
		return columnNames;
	}

	//获取主键
	public String getPrimaryKey(String table) {
		Connection connection = null;
		ResultSet rs = null;

		String key = "";
		try {
			if (connThreadLocal.get() == null) {
				return null;
			}
			connection = connThreadLocal.get();
			DatabaseMetaData dbMeta = connection.getMetaData();
			rs = dbMeta.getPrimaryKeys(null, null, table);
			while (rs.next()) {
				key = rs.getString("COLUMN_NAME");
			}
			return key;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;

	}

}
